package com.base;

import java.util.EmptyStackException;
import java.util.Stack;

import android.app.ActivityManager;
import android.app.NotificationManager;
import android.content.Context;

/**
 * 应用程序Activity管理类：用于Activity管理和应用程序退出
 */
public class AppManager {

	private static Stack<BaseActivity> activityStack;
	private static AppManager instance;

	private AppManager() {
		activityStack = new Stack<BaseActivity>();
	}

	/**
	 * 单一实例
	 */
	public static AppManager getAppManager() {
		if (instance == null) {
			instance = new AppManager();
		}
		return instance;
	}

	/**
	 * 添加Activity到堆栈
	 */
	public synchronized void addActivity(BaseActivity activity) {
		if (activityStack == null) {
			activityStack = new Stack<BaseActivity>();
		}
		activityStack.add(activity);
	}

	public BaseActivity getActivityBackCurrent() {
		try {
			if (activityStack.size() > 1) {
				return activityStack.get(activityStack.size() - 2);
			}
			return currentActivity();
		} catch (EmptyStackException e) {
			return null;
		}
	}

	/**
	 * 获取当前Activity（堆栈中最后一个压入的）
	 */
	public BaseActivity currentActivity() {
		try {
			return activityStack.peek();
		} catch (EmptyStackException e) {
			return null;
		}
	}

	/**
	 * 结束当前Activity（堆栈中最后一个压入的）
	 */
	public void finishActivity() {
		try {
			finishActivity(activityStack.peek());
		} catch (EmptyStackException e) {
		}
	}

	/**
	 * 结束指定的Activity
	 */
	public void finishActivity(BaseActivity activity) {
		if (null != activity) {
			activityStack.remove(activity);
			activity.finish();
			activity = null;
		}
	}

	/**
	 * 结束指定类名的Activity
	 */
	public void finishActivity(Class<? extends BaseActivity> cls) {
		int stackSize = activityStack.size();
		for (int i = stackSize - 1; i >= 0; i--) {
			BaseActivity activity = activityStack.get(i);
			if (null == activity) {
				activityStack.remove(i);
			} else if (activity.getClass().equals(cls)) {
				activityStack.remove(i);
				activity.finish();
				activity = null;
			}
		}
	}

	/**
	 * 结束所有Activity
	 */
	public void finishAllActivity() {
		while (true) {
			try {
				BaseActivity activity = activityStack.pop();
				if (null != activity)
					activity.finish();
			} catch (EmptyStackException e) {
				break;
			}
		}
	}

	/**
	 * 退出应用程序
	 */
	public void AppExit(Context context) {
		try {
			finishAllActivity();
			// 清除通知栏的所有应用相关消息
			((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).cancelAll();

			ActivityManager activityMgr = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
			activityMgr.killBackgroundProcesses(context.getPackageName());
			System.exit(0);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}